/**
 * Created by jt on 2017/5/8.
 */
import "./index.less";
import "../../../unit/common/js/bootstrap_js/select2.min.js";
import "../../../unit/common/js/bootstrap_js/jquery.dataTables.js";
import "../../../unit/common/js/bootstrap_js/form-samples.js";
import "../../../unit/common/js/bootstrap_js/table-editable.js";
import "../../../unit/common/js/bootstrap_js/jquery.jqGrid.src.js";


var token = sessionStorage.getItem('token');
if (token == null || token =='') {
    location.href = HOST_FRT+'/expert_grid/login.html';
}
var grdId = getArgs().id;

var applyList = {
    projId : 0,
    currrTypList: [],
    currTyp : {},
    currVal : {},
    exptNam : '',
    init: function(){
        this.getCurrTyp()
            .then(this.getApplyData)
            .then(this.renderapplyList)
            .then(this.renderPage)
            .then(this.bindEvent);
    },

    // 获取币种
    getCurrTyp:function(){
        let self = applyList;
        return new Promise((resolve, reject)=>{
            var parmTyps = 'CURR_TYP';
            $.ajax({
                url: HOST_ADDR + '/cpmp/comParm/getByParmTyp/' + parmTyps,
                type: 'get',
                dataType: 'json',
                async: false,
                headers: {'access_token': token, 'login_type': 'ums'},
                contentType: 'application/json',
                success: function (resp) {
                    if (!resp.success) {
                        alert(resp.msgCod + " - " + resp.msgInf);
                        console.log(resp.msgCod + " - " + resp.msgInf);
                        return;
                    }
                    if (jQuery.isArray(resp.data)) {
                        for (var i = 0; i < resp.data.length; i++) {
                            self.currrTypList.push(resp.data[i].parmCod);
                            self.currTyp[resp.data[i].parmCod] = resp.data[i].parmMemo;
                            self.currVal[resp.data[i].parmCod] = resp.data[i].parmVal;
                        }
                    }
                    resolve();
                },
                error: function (err) {
                    console.log(err);
                }
            })
        });
    },

    getApplyData: function() {
        let self = applyList;
        return new Promise((resolve, reject)=>{
            $.ajax({
                url: HOST_ADDR + '/cpmp/bidProjOnMngForExpt/showAwdInf/'+grdId,
                type: 'get',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        // isAgreed    0: 初始值  1:同意   2:不同意
                        if(resp.data.bidProjOnExptGrdInf.isAgreed=='1' || resp.data.bidProjOnExptGrdInf.isAgreed=='2'){
                            $(".J_submit").removeClass("hide").remove();
                            var result = resp.data.bidProjOnExptGrdInf.isAgreed=='1' ? "同意" : "不同意" ;
                            $(".projAwdRsn").parent().parent().before("<div class='control-group'>审批结果："+result+"</div>");
                        }
                        resp.data.bidProjOnExptGrdInf.projNam!=null && $(".J_projNam").html(resp.data.bidProjOnExptGrdInf.projNam);
                        resp.data.bidProjOnExptGrdInf.projAwdRsn!=null && $(".projAwdRsn").html(resp.data.bidProjOnExptGrdInf.projAwdRsn);
                        self.projId = resp.data.bidProjOnExptGrdInf.projId;
                        self.exptNam = resp.data.bidProjOnExptGrdInf.exptNam;
                        resolve(resp);
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    },

    // 渲染列表
    renderapplyList: function(resp){
        let self = applyList;
        // 处理数据begin
        var matinfo = resp.data.projOnMatDtls;
        var bidSplrList = resp.data.bidProjOnWinDtls;
        var totalLines = 1;  // 总数据行
        for(var i=0;i<matinfo.length;i++){
            totalLines+=2;
            var qotDtl = [];
            for(var m=0;m<bidSplrList.length;m++){
                if(bidSplrList[m].matId==matinfo[i].id){
                    qotDtl.push(bidSplrList[m]);
                }
            }
            matinfo[i].qotDtls = qotDtl;
        }
        jQuery("#mygrid2").jqGrid({
            width:'100%',
            dataType:'local',
            width:'100%',
            height: 250,
            colNames:['ID','物料编码','物料名称', '计量单位', '招标数量','交货地址','交货日期','备注'],
            colModel:[
                {name:'id',index:'id', width:50,hidden: true},
                {name:'matCod',index:'matCod', width:80},
                {name:'matNam',index:'matNam', width:150},
                {name:'matUnt',index:'matUnt', width:80,align:"center"},
                {name:'pchsNum',index:'pchsNum', width:80,align:"center"},
                {name:'dlvAdr',index:'dlvAdr', width:80},
                {name:'dlvDte',index:'dlvDte', width:120,align:"center"},
                {name:'memo',index:'memo', width:150}
            ],
            subGrid: true,
            fitColumns: true,
            shrinkToFit: true,
            altRows: true,
            // define the icons in subgrid
            subGridOptions: {
                "plusicon"  : "ui-icon-triangle-1-e",
                "minusicon" : "ui-icon-triangle-1-s",
                "openicon"  : "ui-icon-arrowreturn-1-e",
                "reloadOnExpand" : true,
                "selectOnExpand" : true
            },
            subGridRowExpanded: function(subgrid_id, row_id) {
                var subgrid_table_id, pager_id, lastsel;
                subgrid_table_id = subgrid_id+"_t";
                pager_id = "p_"+subgrid_table_id;
                $("#"+subgrid_id).html("<table id='"+subgrid_table_id+"' class='scroll'></table><div id='"+pager_id+"' class='scroll'></div>");
                jQuery("#"+subgrid_table_id).jqGrid({
                    datatype: "local",
                    height: '100%',
                    colNames: ['matId','供应商ID','供应商','币种','币种hidden','定标价格','定标数量','合计','定标交货日期','品牌','备注'],
                    colModel: [
                        {name:"matId",index:"matId",hidden:true},
                        {name:"splrId",index:"splrId",hidden:true},
                        {name:"splrNam",index:"splrNam",width:200, sortable:false},
                        {name:"currTypFmt",index:"currTypFmt",width:70,align:"center", sortable:false,formatter: self.currTypFmatter},
                        {name:"currTyp",index:"currTyp",hidden:true},
                        {name:"untPri",index:"untPri",width:100,align:"center", sortable:false},
                        {name:"pchsNum",index:"pchsNum",width:100,align:"center", classes:"splNum",sortable:false},
                        {name:"ttlPri",index:"ttlPri",width:100,align:"center", sortable:false},
                        {name:"tendDlvDte",index:"tendDlvDte",width:130,align:"center", sortable:false},
                        {name:"matBnd",index:"matBnd",width:100,align:"center", sortable:false},
                        {name:"memo",index:"memo",width:100,align:"center", sortable:false}
                    ],
                    fitColumns: true,
                    shrinkToFit: true,
                    altRows: true
                });
                for(var m=0;m<matinfo[row_id-1].qotDtls.length;m++){
                    totalLines+=1;
                    var subrowid = m+1;
                    var rowinfo = matinfo[row_id-1].qotDtls[m];
                    rowinfo.id = subrowid;
                    rowinfo.tendDlvDte = rowinfo.tendDlvDte ? (new Date(rowinfo.tendDlvDte)).Format("yyyy-MM-dd") : '';
                    rowinfo.currTypFmt = rowinfo.currTyp ? rowinfo.currTyp : '';
                    $("#"+subgrid_table_id).jqGrid('addRowData', subrowid, rowinfo);
                    $("#"+subgrid_table_id+" #"+subrowid).data("rowinfo",rowinfo);
                }
            }
        });
        for ( var i = 0; i < matinfo.length; i++){
            var rowid = i+1;
            matinfo[i].dlvDte = matinfo[i].dlvDte ? (new Date(matinfo[i].dlvDte)).Format("yyyy-MM-dd") : '';
            $("#mygrid2").jqGrid('addRowData', rowid, matinfo[i]);
            $("#mygrid2>tbody>tr#"+rowid+">td").trigger("click");  // 报价信息展开
            if($("#mygrid2_"+rowid+"_t").width()+27<$(".mygrid2").width()){
                $("#mygrid2_"+rowid+"_t").jqGrid('setGridWidth', $(".mygrid2").width()-27);
            }
        }
        jQuery("#mygrid2").jqGrid('setGridWidth', $("#mygrid2_1_t").width()+27);
        console.log('totalLines--->',totalLines);
        jQuery("#mygrid2").jqGrid('setGridHeight', totalLines*30+3*(matinfo.length+1));
        $("#mygrid2>tbody>tr.jqgrow").addClass("bg-lightgray");

    },

    currTypFmatter:function(cellvalue, options, rowObject){
        let self = applyList;
        return self.currTyp[cellvalue];
    },

    // 渲染分页
    renderPage: function(){
        let self = applyList;
        jQuery.ajax({
            url: HOST_ADDR+'/cpmp/bidProjOnMngForPchs/view/'+self.projId,
            type: 'get',
            dataType: 'json',
            contentType:"application/json",
            headers: {
                'access_token': token,'login_type':'ums'
            },
            success: function(resp) {
                if (!resp.success) {
                    alert(resp.msgCod + ' ' + resp.msgInf);
                    return;
                }
                if(resp.data.bidProjOn.projSts=='25'){
                    $(".J_submit").removeClass("hide");
                }else{
                    $(".J_submit").remove();
                }
            },
            error: function (err) {
                console.log(err);
            }
        });
    },

    // 绑定事件
    bindEvent: function(){
        let self = applyList;
        $(".J_submit").on("click",function(){
            var isAgreed = '';
            var projAwdRsn = $(".projAwdRsn").val();
            if($(this).hasClass("agree")){
                isAgreed = '1';
            }else{
                isAgreed = '2';
            }
            if(!$(".projAwdRsn").val().trim()){
                alert("请填写理由！");
                return false;
            }
            var data = {
                "exptNam": self.exptNam,
                "grdId": grdId,
                "isAgreed": isAgreed,
                "projAwdRsn": projAwdRsn
            }
            $.ajax({
                url: HOST_ADDR + '/cpmp/bidProjOnMngForExpt/subAppRes/',
                type: 'post',
                dataType: 'json',
                headers: {
                    'access_token': token,'login_type':'ums'
                },
                data: JSON.stringify(data),
                contentType: "application/json",
                success: function (resp) {
                    if (resp.success) {
                        console.log(resp);
                        alert(resp.msgInf);
                        location.href = HOST_FRT+'/expert_grid/proj_list.html';
                    }
                    else {
                        alert(resp.msgInf);
                    }
                },
                error: function (err) {
                    console.log(err);
                }
            });
        });
    },

    // 渲染列表
    renderList(){
        this.getApplyData()
            .then(this.renderapplyList)
            .then(this.renderPage)
            .then(this.bindEvent);
    }
};

App.init();
applyList.init();

